package com.silentfish.practiceDemo.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Vector;

/**
 * 连接池实现
 */
public class DBConnectionPool {

    private static final Logger LOGGER = LoggerFactory.getLogger(DBConnectionPool.class);

//        }catch (ClassNotFoundException e){
//            LOGGER.error("can not load jdbc driver",e);

    private static Vector<Connection> pool;//连接池
    private static Vector<Connection> poolStatus;//连接池状态
    private Connection conn;        //数据库连接对象
    private Boolean inUse;           //是否被使用
    private long lastAccess;         //最近一次释放该连接的时间
    private int useCount;            //被使用次数

    /**
     * 初始化数据库连接池
     */
    public static synchronized void FastInitPool()throws Exception {
        try {
            Properties conf = PropsUtil.loadProps("config.properties");
            Class.forName(conf.getProperty("jdbc.driver"));
            for (int i=0; i < 10; i++) {//默认设置10个连接
                //创建连接
//                Connection conn = createConnection();创建连接
                Connection conn = null;
                if (conn != null) {
                    //添加到连接池
                    addConnection(conn);
                }
            }
        }catch (Exception e){

        }
    }

    /**
     * 向连接池对象中添加数据库连接
     */
    private static void addConnection(Connection conn) {
        if (pool1 == null || pool2 == null) {
            pool1 = new Vector<Connection>(10);
            pool2 = new Vector<Connection>(10);
        }
        pool1.addElement(conn);
//        pool2.addElement("false");
    }

    /**
     * 获取数据库连接
     */
    public static synchronized Connection getConn() throws Exception {
        Connection conn = null;
        try {
//            if (driver = null){
//                FastInitPool();
//            }

            // 获得一个可用的(空闲的)连接
            for (int i = 0; i < pool1.size(); i++) {
                conn = pool1.elementAt(i);
                if (pool1.elementAt(i) == "false") {
                    pool1.set(i,"true");
                    return conn;
                }
            }

            //如果没有可用连接，且已有连接数小于最大连接数限制，则创建并增加一个新连接到连接池
            conn = createConnection();
            pool.addElement(conn);
            pool1.addElement("true");
        }catch (Exception e) {
            System.err.println(e.getMessage());
            throw new Exception(e.getMessage());
        }
        return conn; //返回一个有效的新连接
    }

    public Connection getConnection(String strDriver, String strUrl, String strUserName, String strPassWord)
            throws SQLException {
        try{
            Class.forName(strDriver);
            conn = DriverManager.getConnection(strUrl, strUserName, strPassWord);
        }catch (ClassNotFoundException e){

        }
        return conn;
    }
}





